﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;

namespace Common.UI.Controls
{
	public class CustomGridView : GridView
	{
        public CustomGridView()
        {
            SizeChanged += CustomGridView_SizeChanged;
        }

        void CustomGridView_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (ItemsPanelRoot != null && ItemsPanelRoot.Children != null)
                foreach (var child in ItemsPanelRoot.Children)
                    Update(child);
        }

        protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
        {
            base.PrepareContainerForItemOverride(element, item);            
            Update(element);
        }

        private void Update(params Object[] elements)
        {
            if (elements == null) return;

            foreach (var element in elements)
            {
                var gvi = element as FrameworkElement;
                if (gvi == null) continue;

                var size = GetSize();                
                gvi.Width = size;
                gvi.Height = size;
            }
            
        }

        private double GetSize()
        {
            if (ActualHeight < 1 || ActualWidth < 1)
                return 170;
            var size = Math.Min(ActualHeight, ActualWidth) / 2;
            return size;
        }
	}
}
